package com.projectsexception.festivales.provider.handlers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.projectsexception.festivales.provider.model.Band;
import com.projectsexception.festivales.provider.model.Show;
import com.projectsexception.festivales.provider.model.Stage;
import com.projectsexception.festivales.provider.util.SAXHandlerUtil;

public class ShowsHandler extends DefaultHandler {
    
    private static final String SHOW_ELEMENT = "show";
    private static final String ID_ATTRIBUTE = "id";
    private static final String BAND_ATTRIBUTE = "band";
    private static final String STAGE_ATTRIBUTE = "stage";
    private static final String DATE_ATTRIBUTE = "date";
    private static final String START_TIME_ATTRIBUTE = "startTime";
    private static final String END_TIME_ATTRIBUTE = "endTime";
    
    private static final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");
    
    private Map<String, Show> shows;
    private Map<String, Band> bands;
    private Map<String, Stage> stages;
    
    public ShowsHandler(Map<String, Band> bands, Map<String, Stage> stages) {
        this.bands = bands;
        this.stages = stages;
    }

    @Override
    public void startDocument() {
        shows = new HashMap<String, Show>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        String s = SAXHandlerUtil.getElementName(localName, qName);
        if (s.equals(SHOW_ELEMENT)) {
            Show showInfo = new Show();
            showInfo.setId(attributes.getValue(ID_ATTRIBUTE));
            showInfo.setBand(bands.get(attributes.getValue(BAND_ATTRIBUTE)));
            showInfo.setStage(stages.get(attributes.getValue(STAGE_ATTRIBUTE)));
            try {
                showInfo.setDate(dateFormatter.parse(attributes.getValue(DATE_ATTRIBUTE)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            showInfo.setStartTime(attributes.getValue(START_TIME_ATTRIBUTE));
            showInfo.setEndTime(attributes.getValue(END_TIME_ATTRIBUTE));
            shows.put(showInfo.getId(), showInfo);
        }
    }

    public Map<String, Show> getResult() {
        return shows;
    }

}
